import os
import PIL.Image
import PIL.ExifTags
import PIL.Image
import PIL.ImageOps
import io
import json
import base64
import requests
import codecs


def apply_exif_orientation(image):
    try:
        exif = image._getexif()
    except AttributeError:
        exif = None

    if exif is None:
        return image

    exif = {
        PIL.ExifTags.TAGS[k]: v
        for k, v in exif.items()
        if k in PIL.ExifTags.TAGS
    }

    orientation = exif.get("Orientation", None)

    if orientation == 1:
        # do nothing
        return image
    elif orientation == 2:
        # left-to-right mirror
        return PIL.ImageOps.mirror(image)
    elif orientation == 3:
        # rotate 180
        return image.transpose(PIL.Image.ROTATE_180)
    elif orientation == 4:
        # top-to-bottom mirror
        return PIL.ImageOps.flip(image)
    elif orientation == 5:
        # top-to-left mirror
        return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
    elif orientation == 6:
        # rotate 270
        return image.transpose(PIL.Image.ROTATE_270)
    elif orientation == 7:
        # top-to-right mirror
        return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
    elif orientation == 8:
        # rotate 90
        return image.transpose(PIL.Image.ROTATE_90)
    else:
        return image


def load_image_file(filename):
    try:
        image_pil = PIL.Image.open(filename)
    except IOError:
        return

    # apply orientation to image according to exif
    image_pil = apply_exif_orientation(image_pil)

    with io.BytesIO() as f:
        ext = os.path.splitext(filename)[1].lower()
        if image_pil.mode == "RGBA":
            image_pil = image_pil.convert("RGB")

        if ext in [".jpg", ".jpeg"]:
            _format = "JPEG"
        else:
            _format = "PNG"

        image_pil.save(f, format=_format)
        f.seek(0)
        return f.read()


def convert2labelme():
    for name in os.listdir(base_dir):
        image_path = os.path.join(result_dir_image, name.split(".")[0] + ".jpg")
        image_data = load_image_file(image_path)

        with codecs.open(os.path.join(base_dir, name), "r", "utf8") as f:
            result = json.loads(f.read())

        save_data = dict()
        save_data["imageData"] = base64.b64encode(image_data).decode("utf-8")
        save_data["version"] = "4.5.6"
        save_data["flags"] = {}
        shapes = []
        for item in result["result"]:
            bbox = item["quad"].split(",")
            label = item["words"]
            sl = [float(axis) for axis in bbox]
            point_dict = dict()
            point_dict["label"] = label
            point_dict["group_id"] = None
            point_dict["shape_type"] = "polygon"
            point_dict["flags"] = dict()
            point_dict["points"] = [[sl[0], sl[1]], [sl[2], sl[3]], [sl[4], sl[5]], [sl[6], sl[7]]]
            shapes.append(point_dict)
        save_data["shapes"] = shapes
        save_data["imagePath"] = image_path
        with codecs.open(os.path.join(result_dir, name.split(".")[0] + ".json"), "a", "utf8") as f2:
            f2.write(json.dumps(save_data, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    IP = "127.0.0.1"
    PORT = "8000"

    base_dir = "/data/projects/own/docs/data"
    result_dir = "/data/ppocr/trainData/test/ydbsLabelme"
    result_dir_image = "/data/ppocr/trainData/test/images"
    convert2labelme()

